package com.jl.tools.stkeditor.control;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

import com.jl.tools.stkeditor.ISTKEditorFrm;
import com.jl.tools.stkeditor.GenTextAndItem;
import com.jl.tools.stkeditor.ResultListenner;
import com.jl.tools.stkeditor.command.AppendCommand;
import com.jl.tools.stkeditor.command.CmdUndoManager;
import com.jl.tools.stkeditor.exception.DataNotMatchCodingScheamException;

/**
 * 
 * @author LuHongjun
 */
public class STKEditorControl {

	private ISTKEditorFrm frm;
	private GenTextAndItem bridge;
	private CmdUndoManager cum;

	public STKEditorControl(ISTKEditorFrm frm) {
		this.frm = frm;
		this.bridge = new GenTextAndItem();
		this.bridge.addObserver((ResultListenner) this.frm);
		cum = new CmdUndoManager();
	}

	public void textChange(String text) {
		try {
			bridge.generateCode(text);
		} catch (DataNotMatchCodingScheamException ex) {
			ex.printStackTrace();
		}
	}

	public void append() {
		AppendCommand appendCmd = new AppendCommand(frm);
		appendCmd.execute();
		cum.add(appendCmd);
	}

	public void undo() {
		if (cum.canUndo()) {
			cum.undo();
		}
	}

	public void save(String path) {
		if(path != null){
			if(!path.endsWith(".txt")){
				path = path + ".txt";
			}
			Writer writer = null;
			try {
				writer = new FileWriter(new File(path), false);
				writer.write(frm.getCommandLinesText());
				writer.flush();
			} catch (FileNotFoundException e1) {
				e1.printStackTrace();
			} catch (IOException e2) {
				if(writer != null){
					try {
						writer.close();
					} catch (IOException e1) {
						e1.printStackTrace();
					}
				}
			} 
		}
	}
}
